package cer.verify;

import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Date;

public class B {

	public static void main(String[] args) throws Exception {
		
		String path = B.class.getResource("").getPath();

		//1）验证证书的有效期
		//（a）获取X509Certificate类型对象
		CertificateFactory cf=CertificateFactory.getInstance("X509");
		FileInputStream in1=new FileInputStream(path+"www.client.com.cer");
		java.security.cert.Certificate c1=cf.generateCertificate(in1);
		X509Certificate t=(X509Certificate)c1;
		in1.close();
		//（b）获取日期
		Date TimeNow=new Date();
		//（c）检验有效性
		try{
		t.checkValidity(TimeNow);
		System.out.println("OK");
		}catch(CertificateExpiredException e){//过期
		System.out.println("Expired");
		System.out.println(e.getMessage());
		}catch(CertificateNotYetValidException e){ //尚未生效
		System.out.println("Too early");
		System.out.println(e.getMessage());}
		//（2）验证证书签名的有效性
		//（a）获取CA证书
		CertificateFactory cf2=CertificateFactory.getInstance("X509");
		FileInputStream in2=new FileInputStream(path+"www.server.com.cer");
		java.security.cert.Certificate cac=cf2.generateCertificate(in2);
		in2.close();
		//（c）获取CA的公钥
		PublicKey pbk=cac.getPublicKey();
		//（b）获取待检验的证书（上步已经获取了，就是C1）
		//（c）检验证书
		boolean pass=false;
		try{
		c1.verify(pbk);
		pass=true;
		}catch(Exception e){
		pass=false;
		System.out.println(e);
		} 
		
		System.out.println("pass=="+pass);
		
	}

}
